<!--
 * @Description: 编辑控件库
 * @Author: wangwangwang
 * @Date: 2020-07-09 19:35:19
 * @LastEditors: wangwangwang
 * @LastEditTime: 2020-07-20 17:43:10
--> 
<template>
  <section class="pages_content" style="height:100%;">
    <div>
      <el-row type='flex' class="handle-title" justify="space-between" align='middle'>
        <el-col :span="12">编辑控件</el-col>
        <el-col :span="12" style="text-align:right;">
          <el-button type="primary">保存</el-button>
        </el-col>
      </el-row>
      <el-row :gutter='15' style="height:100%;padding:0 10px;" class="control-config">
        <el-col :span='4' style="height:100%; overflow:scroll;">
          <div class="control-lib">
            <div class="control-title">
              <el-row type="flex" align="middle" justify="space-between">
                <el-col :span="8" :push="2">控件库</el-col>
                <el-col :span="8">
                  <el-button size="middle" type="text">添加文件夹</el-button>
                </el-col>
              </el-row>
            </div>
            <div class="control-type-container">
              <div class="lib-type-list">
                <div class="list-tile">标准控件库</div>
                <div v-for="(item, index) in commonControlData" :key="item.id" :index='index' draggable="true" class="control-type-list">{{item.name}}</div>
              </div>
            </div>
          </div>
        </el-col>
        <el-col :span='16' style="height:100%; overflow:scroll;">
          <div class="table-container">
            <div class="table-title">
              <el-row type="flex" align="middle" justify="space-between">
                <el-col :span="20">
                  <span>自定义展示<el-input-number v-model="defaultColNum" style="margin:0 10px;" controls-position="right" :min="2" :max="50" @change="handleChange"></el-input-number> </span>
                  <span style="color:#4B4C4D;">列（最多展示50列，最少2列）</span>
                </el-col>
                <el-col :span="4" style="text-align:right;">
                  <el-button type="primary" @click="previewSubmit()">预览</el-button>
                </el-col>
              </el-row>
            </div>
            <div class="table-main">
              <div class="table-backgroud">
                <el-row v-for="item in rowData" :key="item.id" class="backgroud-list">
                  <el-col v-for="list in defaultColNum" :key="list" class="backgroud-col" :style="{width:`${100/defaultColNum}%`}"></el-col>
                </el-row>
              </div>
              <div class="table-list-container">
                <div v-for="(item,index) in rowData" :key="item.id" :class="[(moveRow===index&&(!moveCol2&&moveCol2!==0))?'hover-row':'', 'table-list']" :style="{height:`${item.height*41}px`}" :rowIndex='index'>
                  <div v-for="(list,index2) in item.children" :key="list.id" class="col-list" :rowIndex='index' :colIndex='index2' :style="[{width:`${(list.width)/defaultColNum*100}%`},{height:`${list.height*41}px`}]">
                    <template v-for="(list2,index3) in list.children">
                      <div v-if='list2.type' :key="list2.id" :rowIndex='index' :colIndex='index2' :colIndex2="index3" 
                      :class="['table-col-list',(activeRow===index&&activeColIndex===index2&&activeCol===index3)?'is-active':'']" :style="[{width:`${((list2.titleWidth*1)+(list2.contentWidth*1))/list.width*100}%`},{height:`${list2.rowHeight*41}px`}]" 
                      @click="setActive(index, index2, index3, list2)">
                        <div class="list-title" :style="[{width:`${list2.titleWidth*1/((list2.titleWidth*1)+(list2.contentWidth*1))*100}%`},{height:`${list2.rowHeight*41}px`}]">{{list2.title}}</div>
                        <div class="list-content" :style="[{width:`${list2.contentWidth*1/((list2.titleWidth*1)+(list2.contentWidth*1))*100}%`},{height:`${list2.rowHeight*41}px`}]"></div>
                        <i class="el-icon-error" @click="deleteList($event,index,index2, index3)"></i>
                      </div>
                      <div v-if='!list2.type' :key="list2.id"
                        :class="['table-col-list',(moveCol===index2&&moveCol2===index3&&moveRow===index)?'hover-col':'']"
                        :rowIndex='index' :colIndex='index2' :colIndex2="index3"
                        :style="[{width: '100%'},{height:`${list2.rowHeight*41}px`}]">
                      </div>
                    </template>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </el-col>
        <el-col :span='4' style="height:100%; overflow:scroll;">
          <div class="config-container">
            <div class="config-container-title">
              {{activeData.name}}
            </div>
            <div class="config-flex">
              <div style="margin-bottom: 10px;">
                标题占位<el-input v-model="activeData.titleWidth" class="flex-list" @change="changeTitleWidth"></el-input>列
              </div>
              <div style="margin-bottom: 10px;">
                内容占位<el-input v-model="activeData.contentWidth" class="flex-list" @change="changeContentWidth"></el-input>列
              </div>
              <div style="margin-bottom: 10px;">
                控件占位<el-input v-model="activeData.rowHeight" class="flex-list" @change="changeRow"></el-input>行
              </div>
            </div>
            <div style="padding: 17px 20px;">
              <div class="config-list">
                <div class="config-title">标题 <span>最多20个字</span></div>
                <el-input v-model="activeData.title" class="flex-list"></el-input>
              </div>
              <div class="config-list">
                <div class="config-title">提示文字 <span>最多20个字</span></div>
                <el-input v-model="activeData.placeholder" class="flex-list"></el-input>
              </div>
            </div>
          </div>
        </el-col>
      </el-row>
      <el-dialog v-dialogDrag
        :visible.sync="previewVisible"
        title="表单预览"
        width="80%">
        <PreviewModal :previewData="previewData" :defaultColNum="defaultColNum"/>
        <span slot="footer" class="dialog-footer">
          <el-button @click="previewVisible = false">取 消</el-button>
          <el-button type="primary" @click="previewVisible = false">确 定</el-button>
        </span>
      </el-dialog>
    </div>
  </section>
</template>
<script>
import PreviewModal from './component/PreviewModal';
export default {
  components: {
    PreviewModal,
	},
  data () {
    return {
      previewVisible: false,
      previewData: [],
      commonControlData: [{
        name: '单行输入框',
        id: 1
      }, {
        name: '多行输入框',
        id: 2
      }, {
        name: '单选框',
        id: 3
      }, {
        name: '多选框',
        id: 4
      }, {
        name: '下拉框',
        id: 5
      }, {
        name: '日期',
        id: 6
      }, {
        name: '附件',
        id: 7
      }, {
        name: '文本框',
        id: 8
      }],
      rowNum: 100,
      defaultColNum: 10, // 默认列
      defaultHeightNum: 1, // 默认高度
      defaultTitleWidth: 1, // 默认标题宽度
      defaultContentWidth: 3, // 默认内容宽度
      moveRow: '',
      moveCol2: '',
      moveCol: '',
      activeRow: 0,
      activeColIndex: 0,
      activeCol: 0,
      rowData: [],
      realRowData: [],
      activeData: {},
      currentIndex: '',
    }
  },
  methods: {
    /**
     * @Description: 预览
     * @Param: 
     * @Author: wangwangwang
     */
    previewSubmit () {
      const newArry = this.rowData.filter((item) => (
        item.children.length > 0
      ));
      if (!newArry.length) {
        this.$message({
          message: '请存在数据后在进行预览！！！',
          type: 'warning'
        });
        return
      }
      console.log(newArry)
      this.previewData = newArry;
      this.previewVisible = true;
    },
    /**
     * @Description: 设置表单标题和内容的占位宽度
     * @Param: 
     * @Author: wangwangwang
     */
    changeTitleWidth (value) {
      if (isNaN(value)) {
        this.activeData.titleWidth = 1
        this.$message({
          message: '只能输入数字！！！',
          type: 'warning'
        });
      } else if (value * 1 === 0) {
        this.activeData.titleWidth = 1
        this.$message({
          message: '占位不能为0！！！',
          type: 'warning'
        });
      } else {
        value = value * 1;
        const onSelf = this.realRowData[this.activeRow].children[this.activeColIndex].children[this.activeCol]
        const onSelfParent = this.realRowData[this.activeRow].children
        let allWidth = 0;
        for (let i = 0; i < onSelfParent.length; i+=1) {
          if (i !== this.activeColIndex && !onSelfParent[i].isEmpty) {
            allWidth+=onSelfParent[i].width
          }
        }
        allWidth = allWidth + onSelf.contentWidth + value;
        if (allWidth > this.defaultColNum) {
          this.$message({
            message: '占位的列数不能大于总列数！！！',
            type: 'warning'
          });
          return
        } else if (allWidth === this.defaultColNum) {
          onSelf.titleWidth = value;
          onSelfParent[this.activeColIndex].width = value + onSelf.contentWidth;
          onSelfParent[onSelfParent.length-1].width = 0;
          this.rowData = [...this.realRowData];
        } else {
          onSelf.titleWidth = value;
          onSelfParent[this.activeColIndex].width = value + onSelf.contentWidth;
          onSelfParent[onSelfParent.length-1].width = this.defaultColNum - allWidth;
          this.rowData = [...this.realRowData];
        }
      }
    },
    changeContentWidth (value) {
      if (isNaN(value)) {
        this.activeData.contentWidth = 2
        this.$message({
          message: '只能输入数字！！！',
          type: 'warning'
        });
      } else if (value * 1 === 0) {
        this.activeData.contentWidth = 2
        this.$message({
          message: '占位不能为0！！！',
          type: 'warning'
        });
      } else {
        value = value * 1
        const onSelf = this.realRowData[this.activeRow].children[this.activeColIndex].children[this.activeCol];
        const onSelfParent = this.realRowData[this.activeRow].children;
        let allWidth = 0;
        for (let i = 0; i < onSelfParent.length; i+=1) {
          if (i !== this.activeColIndex && !onSelfParent[i].isEmpty) {
            allWidth+=onSelfParent[i].width
          }
        }
        allWidth = allWidth + onSelf.titleWidth + value;
        if (allWidth > this.defaultColNum) {
          this.$message({
            message: '占位的列数不能大于总列数！！！',
            type: 'warning'
          });
          return
        } else if (allWidth === this.defaultColNum) {
          onSelf.contentWidth = value;
          onSelfParent[onSelfParent.length-1].width = 0;
          onSelfParent[this.activeColIndex].width = value + onSelf.titleWidth;
          this.rowData = [...this.realRowData];
        } else {
          onSelf.contentWidth = value;
          onSelfParent[this.activeColIndex].width = value + onSelf.titleWidth;
          onSelfParent[onSelfParent.length-1].width = this.defaultColNum - allWidth;
          this.rowData = [...this.realRowData];
        }
      }
    },
    /**
     * @Description: 改变行数
     * @Param: 
     * @Author: wangwangwang
     */
    changeRow (value) {
      if (isNaN(value)) {
        this.activeData.rowHeight = this.defaultHeightNum;
        this.$message({
          message: '只能输入数字！！！',
          type: 'warning'
        });
      } else if (value * 1 === 0) {
        this.activeData.rowHeight = this.defaultHeightNum;
        this.$message({
          message: '占位不能为0！！！',
          type: 'warning'
        });
      } else {
        value = value * 1
        const onSelf = this.realRowData[this.activeRow].children[this.activeColIndex].children[this.activeCol];
        const onSelfParent = this.realRowData[this.activeRow].children[this.activeColIndex].children;
        let allHeight = 0;
        for (let i = 0; i < onSelfParent.length; i+=1) {
          if (i !== this.activeCol) {
            allHeight += onSelfParent[i].rowHeight
          }
        }
        allHeight = allHeight + value;
        this.realRowData[this.activeRow].children[this.activeColIndex].height = allHeight;
        onSelf.rowHeight = value;
        this.formartRow()
      }
    },
    /**
     * @Description: 设置行后格式化其他列的行
     * @Param: 
     * @Author: wangwangwang
     */
    formartRow () {
      /**
       * @Description: 设置最外层的table-list的高度
       * @Param: 
       * @Author: wangwangwang
       */
      const firstLayer = this.realRowData[this.activeRow].children;
      let maxHeight = 0;
      for (let i = 0; i < firstLayer.length; i+=1) {
        if ((firstLayer[i].height > maxHeight)) {
          maxHeight = firstLayer[i].height
        }
      }
      this.realRowData[this.activeRow].height = maxHeight;
      /**
       * @Description: 格式化table-list
       * @Param: 
       * @Author: wangwangwang
       */
      for (let i = 0; i < firstLayer.length; i+=1) {
        if (maxHeight > firstLayer[i].height) {
          firstLayer[i].height = maxHeight;
          let allHeight = 0;
          for (let j = 0; j < firstLayer[i].children.length; j+=1) {
            allHeight+=firstLayer[i].children[j].rowHeight
          }
          allHeight = maxHeight - allHeight;
          const newArry = []
          for (let k = 0; k < allHeight; k+=1) {
            const data = {
              titleWidth: this.defaultTitleWidth,
              contentWidth: this.defaultContentWidth,
              rowHeight: this.defaultHeightNum,
              id: firstLayer[i].children.length+k+1,
            }
            newArry.push(data)
          }
          firstLayer[i].children = firstLayer[i].children.concat(newArry);
        } else if (maxHeight < firstLayer[i].height) {
          console.log('减少')
        }
      }
    },
    /**
     * @Description: 计算行的总长度
     * @Param: 
     * @Author: wangwangwang
     */
    calWidth (children) {
      let allWidth = 0;
      for (let i = 0; i < children.length; i+=1) {
        allWidth+=children[i].width * 1
      }
      return allWidth;
    },
    /**
     * @Description: 点击表单进行配置
     * @Param: 
     * @Author: wangwangwang
     */
    setActive (index1, index2, index3, data) {
      this.activeRow = index1;
      this.activeColIndex = index2;
      this.activeCol = index3;
      this.activeData = {...data};
    },
    /**
     * @Description: 删除列数据
     * @Param: 
     * @Author: wangwangwang
     */
    deleteList (e,rowIndex, colIndex, colIndex2) {
      e.stopPropagation()
      let copyData = this.rowData[rowIndex].children[colIndex].children[colIndex2];
      const data = {
        contentWidth: copyData.contentWidth,
        rowHeight: copyData.rowHeight,
        titleWidth: copyData.titleWidth,
      }
      for (let i = 0; i < this.rowData.length; i+=1) {
        if (i === rowIndex) {
          for (let j = 0; j < this.rowData[i].children.length; j+=1) {
            if (j === colIndex) {
              for (let k = 0; k < this.rowData[i].children[j].children.length; k+=1) {
                if (k === colIndex2) {
                  this.rowData[i].children[j].children[k] = data
                }
              }
            }
          }
        }
      }
      this.activeData = {};
      this.activeRow = '';
      this.activeColIndex = '';
      this.activeCol = '';
    },
    initFormmatRow () {
      this.rowData = [];
      this.realRowData = [];
      for (let i = 0; i < this.rowNum; i+=1) {
        const data = {
          children: [],
          height: this.defaultHeightNum,
          id: i,
        }
        this.rowData.push(data);
        this.realRowData.push(data);
      }
    },
    handleChange () {
      this.initFormmatRow()
    },
  },
  mounted () {
    this.initFormmatRow();
    const self = this;
    /**
     * @Description: 获取被拖拽的节点
     * @Param: 
     * @Author: wangwangwang
     */
    document.querySelector(".control-config").addEventListener("dragstart", function(event) {
      self.currentIndex = event.target.attributes[1].value * 1;
    });
    /**
     * @Description: 拖拽进行中的判断
     * @Param: 
     * @Author: wangwangwang
     */
    document.querySelector(".control-config").addEventListener("dragover", function(event) {
      event.preventDefault();
    });
    /**
     * @Description: 设置拖拽
     * @Param: 
     * @Author: wangwangwang
     */
    document.querySelector(".control-config").addEventListener("dragenter", function(event) {
      event.preventDefault();
      /**
       * @Description: 当节点为tableList的时候判断是否存在内容，存在内容就就进行如何操作，不存在内容就将其特殊处理
       * @Param: 
       * @Author: wangwangwang
       */
      if (event.target.className === 'table-list') {
        self.moveRow = event.target.attributes[1].value * 1;
        self.moveCol = '';
        self.moveCol2 = '';
      } else if (event.target.className === 'table-col-list') {
        self.moveRow = event.target.attributes[1].value * 1;
        self.moveCol = event.target.attributes[2].value * 1;
        self.moveCol2 = event.target.attributes[3].value * 1;
      } else {
        self.moveRow = '';
        self.moveCol = '';
        self.moveCol2 = '';
      }
    });
    /**
     * @Description: 结束拖拽
     * @Param: 
     * @Author: wangwangwang
     */
    document.querySelector(".control-config").addEventListener("drop", function(event) {
      event.preventDefault();
      const { realRowData, currentIndex, commonControlData } = self;
      self.moveRow = ''
      self.moveCol = ''
      self.moveCol2 = '';
      window.setTimeout(()=>{
        if (event.target.className === 'table-list') {
          const currentRow = event.target.attributes[1].value * 1;
          const { children } = realRowData[currentRow];
          const allWidth = self.calWidth(children)
          if (self.defaultColNum < (allWidth + self.defaultTitleWidth + self.defaultContentWidth)) {
            self.$message({
              message: '占位的列数不能大于总列数！！！',
              type: 'warning'
            });
            return
          }
          const data = [{
            children: [{
              name: commonControlData[currentIndex].name,
              title: '标题',
              placeholder: '请输入',
              type: commonControlData[currentIndex].id,
              titleWidth: self.defaultTitleWidth,
              contentWidth: self.defaultContentWidth,
              rowHeight: self.defaultHeightNum,
            }],
            width: self.defaultTitleWidth + self.defaultContentWidth,
            height: self.defaultHeightNum,
          },{
            children: [{
              titleWidth: self.defaultTitleWidth,
              contentWidth: self.defaultContentWidth,
              rowHeight: self.defaultHeightNum,
              isEmpty: true,
            }],
            isEmpty: true,
            height: self.defaultHeightNum,
            width: self.defaultColNum - (allWidth + self.defaultTitleWidth + self.defaultContentWidth),
          }]
          for (let i = 0; i < self.realRowData.length; i+=1) {
            if (i === currentRow) {
              self.realRowData[i].children = self.realRowData[i].children.concat(data);
            }
          }
          self.rowData = Object.assign([], self.realRowData);
          self.activeData = self.rowData[currentRow].children[0].children[0];
          self.activeRow = currentRow;
          self.activeColIndex = 0;
          self.activeCol = 0;
        } else if (event.target.className === 'table-col-list') {
          const rowIndex = event.target.attributes[1].value * 1;
          const colIndex = event.target.attributes[2].value * 1;
          const colIndex2 = event.target.attributes[3].value * 1;
          const parentCol = realRowData[rowIndex].children[colIndex];
          if (parentCol.width < (self.defaultTitleWidth + self.defaultContentWidth)) {
            self.$message({
              message: '占位的列数不能大于总列数！！！',
              type: 'warning'
            });
            return
          } else if (parentCol.width === (self.defaultTitleWidth + self.defaultContentWidth)) {
            const data = {
              name: commonControlData[currentIndex].name,
              title: '标题',
              placeholder: '请输入',
              type: commonControlData[currentIndex].id,
              titleWidth: self.defaultTitleWidth,
              contentWidth: self.defaultContentWidth,
              rowHeight: self.defaultHeightNum,
            }
            parentCol.children[colIndex2] = data;
            self.rowData = Object.assign([], realRowData);
          } else {
            const copyData = Object.assign([], realRowData[rowIndex].children[realRowData[rowIndex].children.length - 1]);
            const data = {
              name: commonControlData[currentIndex].name,
              title: '标题',
              placeholder: '请输入',
              type: commonControlData[currentIndex].id,
              titleWidth: self.defaultTitleWidth,
              contentWidth: self.defaultContentWidth,
              rowHeight: self.defaultHeightNum,
            }
            parentCol.children[colIndex2] = data;
            /**
             * @Description: 同时修改本列和最后一列的宽度
             * @Param: 
             * @Author: wangwangwang
             */  
            let maxWidth = 0
            for (let i = 0; i < parentCol.children.length; i+=1) {
              const sumWidth = parentCol.children[i].titleWidth + parentCol.children[i].contentWidth;
              maxWidth = sumWidth > maxWidth ? sumWidth: maxWidth
            }
            parentCol.width = maxWidth;
            parentCol.isEmpty = false;
            let minWidth = self.defaultColNum;
            for (let i = 0; i < realRowData[rowIndex].children.length; i+=1) {
              minWidth-=realRowData[rowIndex].children[i].width
            }
            const newArry = []
            for (let i = 0; i < copyData.children.length; i+=1) {
              const data = {
                titleWidth: self.defaultTitleWidth,
                contentWidth: self.defaultContentWidth,
                rowHeight: self.defaultHeightNum,
                id: i,
              }
              newArry.push(data)
            }
            const newData = {
              width: minWidth,
              height: copyData.height,
              isEmpty: true,
              children: newArry
            }
            realRowData[rowIndex].children.push(newData);
            self.rowData = Object.assign([], realRowData);
          }
          self.activeData = self.rowData[rowIndex].children[colIndex].children[colIndex2];
          self.activeRow = rowIndex;
          self.activeColIndex = colIndex;
          self.activeCol = colIndex2;
        }
      },100)
    });
  }
}
</script>
<style lang="scss" scoped>
.handle-title{
  background:linear-gradient(180deg,rgba(250,252,255,1) 0%,rgba(245,247,250,1) 100%);
  margin-bottom: 20px;
  padding: 15px 10px;
}
.control-lib{
  border:1px solid rgba(225,229,237,1);
  border-radius: 4px;
  .control-title{
    padding: 15px 0;
    background:rgba(245,247,250,1);
    border-bottom: 1px solid rgba(225,229,237,1);
  }
  .lib-type-list{
    .list-tile{
      background:rgba(250,252,255,1);
      padding: 15px 10px;
      margin-bottom: 14px;
    }
    .control-type-list{
      background:rgba(245,247,250,1);
      border-radius:4px;
      margin: 0 25px 8px;
      padding: 8px;
      color: #4B4C4D;
      font-size: 12px;
    }
  }
}
.table-container{
  border:1px solid rgba(225,229,237,1);
  border-radius: 4px;
  .table-title{
    background:rgba(245,247,250,1);
    padding: 17px 20px;
    border-bottom:1px solid rgba(225,229,237,1);
  }
  .table-main{
    position: relative;
    height: 500px;
    .table-backgroud{
      height: 500px;
      background: #f9fcff;
      width: 100%;
      position: absolute;
      z-index: 1;
      top: 0;
      left: 0;
      .backgroud-list{
        border-bottom: 1px dashed #E1E5ED;
        .backgroud-col{
          height: 40px;
          border-right: 1px dashed #E1E5ED;
        }
        .backgroud-col:last-of-type{
          border: none;
        }
      }
    }
    .table-list-container{
      height: 500px;
      width: 100%;
      position: absolute;
      top: 0;
      left: 0;
      z-index: 2;
      .hover-row{
        border-top: 1px solid $bg_color;
      }
      .table-list{
        width: 100%;
        .hover-col{
          border-top: 1px solid $bg_color;
        }
        .list-title{
          height: 40px;
          line-height: 40px;
          float: left;
          padding-right: 10px;
          text-align: right;
        }
        .list-content{
          height: 40px;
          line-height: 40px;
          border-radius: 4px;
          background: #fff;
          position: relative;
          float: left;
          border: 1px solid #E1E5ED;
          color: #969799;
          padding-left: 10px;
        }
        .col-list{
          float: left;
          position: relative;
          .table-col-list{
            position: relative;
            .el-icon-error{
              position: absolute;
              top: -5px;
              right: -5px;
              cursor: pointer;
              color: #4B4C4D;
              display: none;
            }
          }
          .is-active{
            border: 1px solid $bg_color;
            box-sizing: border-box;
            .el-icon-error{
              position: absolute;
              top: -5px;
              right: -5px;
              cursor: pointer;
              color: #4B4C4D;
              display: block !important;
            }
          }
        }
      }
    }
  }
}
.config-container{
  border:1px solid rgba(225,229,237,1);
  border-radius: 4px;
  .config-container-title{
    background:rgba(245,247,250,1);
    padding: 17px 20px;
    border-bottom:1px solid rgba(225,229,237,1);
  }
  .config-flex{
    padding: 17px 20px;
    border-bottom: 1px solid #F5F7FA;
    .flex-list{
      width: 50%;
      margin: 0 5px;
    }
  }
}
.config-list{
  margin: 8px 0;
  .config-title {
    font-size: 14px;
    margin-bottom: 5px;
    span{
      font-size: 12px;
      color: #969799;
    }
  }
}

</style>
